package edu.nju.desserthouse.dao.impl;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import nju.edu.desserthouse.model.Sale;

import edu.nju.desserthouse.dao.SaleDao;

/**
 * Session Bean implementation class SaleDao
 */
@Stateless
public class SaleDaoBean implements SaleDao{

	private static final long serialVersionUID = 1L;
	
	@PersistenceContext(unitName = "desserthouseJPA")
	protected EntityManager em;
	
	public SaleDaoBean(){
		
	}

	@Override
	public boolean save(Sale sale) {
		try{
			em.persist(sale);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}

	@Override
	public Sale find(String column, String value) {
		Sale sale = null;
		try{
			Query query = em.createQuery("from Sale s where s." + column + "=" + value);
			sale = (Sale)query.getSingleResult();
			em.clear();
			return sale;
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean updateBySaleId(Sale sale) {
		try{
			em.merge(sale);
		}catch(Exception e){
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	@Override
	public ArrayList<Sale> getSaleList() {
		try{
			Query query = em.createQuery("from Sale s where s.id > -1");
			@SuppressWarnings("unchecked")
			List<Sale> sale = query.getResultList();
			if(sale != null){
				ArrayList<Sale> saleList = new ArrayList<Sale>(sale);
				em.clear();
				return saleList;
			}else{
				System.out.println("NULL RESULT!!!");
				em.clear();
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
	
	@Override
	public ArrayList<Sale> getSaleList(long id) {
		try{
			Query query = em.createQuery("from Sale s where s.vip = " + Long.toString(id));
			@SuppressWarnings("unchecked")
			List<Sale> sale = query.getResultList();
			if(sale != null){
				ArrayList<Sale> saleList = new ArrayList<Sale>(sale);
				em.clear();
				return saleList;
			}else{
				System.out.println("NULL RESULT!!!");
				em.clear();
				return null;
			}
		}catch(Exception e){
			e.printStackTrace();
			return null;
		}
	}
}
